package core

import (
	"fmt"
	"github.com/APP/global"
	"os"
	"time"

	"github.com/gin-gonic/gin" // 引入 Gin Web 框架
)

// 定义 ANSI 终端颜色转义序列
var (
	green   = "\033[32m" // 绿色：成功状态码
	white   = "\033[97m" // 白色：重定向状态码
	yellow  = "\033[33m" // 黄色：客户端错误
	red     = "\033[31m" // 红色：服务器错误或 DELETE 方法
	blue    = "\033[34m" // 蓝色：GET 方法
	magenta = "\033[35m" // 品红：备用
	cyan    = "\033[36m" // 青色：POST 方法
	reset   = "\033[0m"  // 重置颜色
)

// 根据 HTTP 状态码返回对应颜色字符串
func colorForStatus(code int) string {
	switch {
	case code >= 200 && code < 300: // 2xx 成功
		return green
	case code >= 300 && code < 400: // 3xx 重定向
		return white
	case code >= 400 && code < 500: // 4xx 客户端错误
		return yellow
	default: // 5xx 或其他错误
		return red
	}
}

// 根据 HTTP 方法返回对应颜色字符串
func colorForMethod(method string) string {
	switch method {
	case "GET":
		return blue
	case "POST":
		return cyan
	case "PUT":
		return yellow
	case "DELETE":
		return red
	case "PATCH":
		return green
	case "OPTIONS":
		return white
	default:
		return reset // 其他方法无颜色
	}
}

// GinZapColorLogger 返回一个 Gin 中间件，用于同时记录控制台彩色日志 + 文件日志
func GinZapColorLogger() gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		path := c.Request.URL.Path
		method := c.Request.Method
		clientIP := c.ClientIP()

		defer func() {
			latency := time.Since(start)
			statusCode := c.Writer.Status()

			coloredLog := fmt.Sprintf(
				"[GIN] %s |%s %3d %s| %13v | %15s |%s %-7s %s %#v\n",
				start.Format("2006/01/02 - 15:04:05"),
				colorForStatus(statusCode), statusCode, reset,
				latency,
				clientIP,
				colorForMethod(method), method, reset,
				path,
			)
			fmt.Fprint(os.Stdout, coloredLog)

			plainLog := fmt.Sprintf(
				"[GIN] %s | %3d | %13v | %15s | %-7s %#v",
				start.Format("2006/01/02 - 15:04:05"),
				statusCode,
				latency,
				clientIP,
				method,
				path,
			)

			global.APP_LOG.Info(plainLog)
			_ = global.APP_LOG.Sync() // 强制 zap 写入
		}()

		c.Next()
	}
}
